import api from '../../../fetch/api'

export default {
  data() {
    return {
      bigImgPath: '',
      isMoreSetShow:false,
      selFileName:'',
      handleStatus:'new',//new-新增，edit-编辑,
      isShowfileInput:true,
      afterMonthArr: [new Date(moment().format('YYYY-MM-DD 00:00:00')),
      new Date(
        moment()
          .add(30, 'days')
          .format('YYYY-MM-DD 23:59:59')
        )]
    }
  },
  created() {
    this.toBase(this)
  },
  computed: {
    inputParkstr: function (val) {
      return this.favourableModalData.inputParks.join('/')
    },
    selFileNameInput: function(val){
      if(this.selFileName == ''){
        return '未选择任何文件'
      }else{
        if(this.handleStatus == 'edit'){
          this.isShowfileInput = true
        }
        return this.selFileName
      }
    }
  },
  watch: {
    'favourableModalData.reliefType': function (newValue) {
      var self = this;
      if (self.$refs && self.$refs.favourable_form) {
        setTimeout(function () {
          if (self.favourableModalData.reliefType == "1") {
            self.$refs.favourable_form.validateField('faceValue1');
          }
          if (self.favourableModalData.reliefType == "2") {
            self.$refs.favourable_form.validateField('faceValue2');
          }

        }, 200);
      }
    },
    handleStatus(){
      if(this.handleStatus == 'new'){
        this.isShowfileInput = true
      }else if(this.handleStatus == 'edit'){
        this.isShowfileInput =false
      }
    },
    selFileName(val){
      if(this.handleStatus == 'edit'&&val==''){
        this.isShowfileInput = false
      }else{
        this.isShowfileInput = true
      }
    }
  },
  methods: {
    getList() {
      let params = $.extend({}, this.searchParams, this.otherParams);
      this.getItemList(params);
    },
    //文件转bas64
    toBase(vm) {
      var _self = this
      $(document).on('change', "#favourablefile", function () {
        var v = $(this).val();
        var reader = new FileReader();
        if(this.files[0]){
          _self.selFileName = this.files[0].name
        }else{
          _self.selFileName = ''
        }
        reader.readAsDataURL(this.files[0]);
        reader.onload = function (e) {
          vm.favourableModalData.specialUserFile = e.target.result.replace(/data:(.)*;base64,/, "");
        };
      });

    },
    initApplyObjStr: function (params) { //特定用户和其他三个互斥   但选择特定用户时  其他自动取消选择
      var _this = this;

      function removeByValue(arr, val) {
        for (var i = 0; i < arr.length; i++) {
          if (arr[i] == val) {
            arr.splice(i, 1);
            break;
          }
        }
      }
      if (Number(params) == 3) { //表示当前选中特定用户模式
        setTimeout(function () {
          _this.favourableModalData.applyObjStr = ["3"];
        }, 10)
      } else {
        setTimeout(function () {
          removeByValue(_this.favourableModalData.applyObjStr, "3")
        }, 10)
      }
    },
    openSelectParkModal() {
      var _self = this;
      _self.toOpenModal('selectParkModal', 2);
      this.initParkTree("ParkTree");
    },
    initParkTree(treeId) {
      var _self = this;
      api.fetchGet('/compaign/getParkingBaseDataTree.do', {})
        .then(res => {
          //start..
          var data = res;
          if (data != null) {
            var nodes = data.data;
            var jsonStr = JSON.stringify(nodes);

            jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
            nodes = JSON.parse(jsonStr);
            var settings = {
              check: {
                enable: true,
                chkStyle: "checkbox",
                radioType: "all"
              },
              view: {
                showIcon: false,
                showLine: false,
              },
              callback: {
                onClick: function (event, treeId, treeNode) {
                  var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                  treeObj.checkNode(treeNode, true, false);
                  if (treeNode.isArea) {
                    return;
                  }
                },
              }
            };

            $.fn.zTree.destroy("ParkTree");

            var treeObj = $.fn.zTree.init($("#ParkTree"), settings, nodes);
            var treeObj = $.fn.zTree.getZTreeObj("ParkTree");
            for (var i = 0; i < _self.favourableModalData.parkIdList.length; i++) {
              var node = treeObj.getNodeByParam("value", _self.favourableModalData.parkIdList[i]);
              if (node) {
                if (node.getParentNode() && !node.getParentNode().open) {
                  treeObj.expandNode(node.getParentNode(), true, true, true);
                }
                treeObj.checkNode(node, true, true);
              }
            }
            treeObj.expandAll(true);

          } else {
            _self.showToast('暂时没有停车场可选', 2, 3000);
          }
        }, err => {})

    },
    getFirst(val){//停车场树很深，循环获取children
      var _self = this
      if(val.children){
        if(val.children.length>0){
          _self.getFirst(val.children[0])
        }else{
          
        }
      }else if(val.parkId){
        _self.favourableModalData.inputParks.push(val.name)
        _self.favourableModalData.parkIdList.push(val.value)
      }
    },
    getParkTreeFirst(){//获取停车场树第一个内容
      var _self = this;
      api.fetchGet('/compaign/getParkingBaseDataTree.do', {})
        .then(res => {
          //start..
          var data = res;
          if (data != null) {
            this.getFirst(data.data)
          } else {
            _self.showToast('暂时没有停车场可选', 2, 3000);
          }
        }, err => {})
    },
    selectParkSure() {
      var self = this,
        nodes = [];
      var treeObj = $.fn.zTree.getZTreeObj("ParkTree");
      nodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
      var parkList = new Array();
      // 初始化表格显示数据以及提交的表格参数
      self.tableData = {
        ParkNameList: [],
        parkIdList: [],
        parkVipTypeId: [],
        parkItems: [],
      };
      for (var i = 0; i < nodes.length; i++) {
        if (!nodes[i].isArea) {
          parkList.push(nodes[i]);
        }
      }
      if (parkList.length <= 0) {
        self.showToast('请选择一个停车场', 0);
        return;
      }
      self.favourableModalData.parkIdList = [];
      self.favourableModalData.inputParks = [];
      for (var i = 0; i < parkList.length; i++) {
        // self.entity.parkList.push(parkList[i].value);
        self.favourableModalData.parkIdList.push(parkList[i].value);
        self.favourableModalData.inputParks.push(parkList[i].name);
      }
      self.closed('selectParkModal', 2);
      // self.getParkItems();
    },
    cellhanlder(type, id, bodyText) {
      let self = this
      if(!this.selectionList.length && !id){
        this.showToast('请先选择一条记录',0)
        return;
      }else if (this.selectionList.length > 0 || id) {
        self.showDialog(bodyText, ['确认','取消'], function(){
          var idList = [];
          var params = {};
          if (id) {
            params.ids = id
          } else {
            self.selectionList.forEach(function (element) {
              idList.push(element.id)
            });
            params.ids = idList.join(',');
          }
          switch (type) {
            case 'DT': //删除优惠
              params.validStatus = 'DEL';
              self.function_comfirm_callback(params)
              break;
            case 'QY': //启用
              params.validStatus = 'VALID';
              self.function_comfirm_callback(params)
              break;
            case 'DJ': //冻结
              params.validStatus = 'FROZE';
              self.function_comfirm_callback(params)
              break;
            case 'DL': //下载内部二维码
              params.validStatus = '';
              self.Download_qr_codes_callback(params)
              break;
            default:
              break;
          }
        })
      }
    },
    function_comfirm_callback(params) {
      api.fetchGet('/compaign/updateStatus.do', params)
        .then(res => {
          // icon: 0:普通提示 1：正确的提示 2： 错误提示
          // time: 不填默认1000ms
          this.showToast(res.message, 1, 2000)
          this.getList();
        }, err => {
          
        })
    },
    Download_qr_codes_callback(params) {
      function downloadFile(url) {
        try {
          var elemIF = document.createElement("iframe");
          elemIF.src = url;
          elemIF.style.display = "none";
          document.body.appendChild(elemIF);
        } catch (e) {

        }
      };
      api.fetchGet('/compaign/downQr.do', params)
        .then(res => {
          // icon: 0:普通提示 1：正确的提示 2： 错误提示
          // time: 不填默认1000ms
          this.showToast(res.message, 1, 2000)
          res.data.forEach(function (val) {
            var url = "/mgr/common/download.do?" + "fileName=" + val.fileName + "&format=" + val.format + "&downName=" + val.name;
            downloadFile(url);
          })
          this.getList();
        }, err => {
          // this.showToast(err.data.message, 2, 5000)
        })
    },
    ParkListModal_open(row) {
      let self = this;
      let params = {
        'compaignId': row.id
      }
      api.fetchGet('/compaign/parkList.do', params)
        .then(res => {
          self.ParkListModalData.list = res.data;
          this.toOpenModal('ParkListModal');
        }, err => {})
    },
    SpecificUserModal_open(index) {
      let self = this;
      self.SpecificUserModalData.query_carCode = '';
      self.SpecificUserModalData.query_compaignId = self.tbodysInfo[index].id;
      let params = {
        query_compaignId: self.tbodysInfo[index].id,
        page: 1,
        rp: 10000,
        query_carCode: self.SpecificUserModalData.query_carCode,
      };

      api.fetchGet('/compaign/specialUserList.do', params)
        .then(res => {
          self.SpecificUserModalData.list = res.data.rows;
          this.toOpenModal('SpecificUserModal');
        }, err => {})
    },
    SpecificUserModalData_change() {
      let self = this;
      let params = {
        query_compaignId: self.SpecificUserModalData.query_compaignId,
        page: 1,
        rp: 10000,
        query_carCode: self.SpecificUserModalData.query_carCode,
      };
      console.log('SpecificUserModalData_change', this.tbodysInfo, self.SpecificUserModalData.query_compaignId)

      api.fetchGet('/compaign/specialUserList.do', params)
        .then(res => {
          console.log('getListResult', res, res.data.rows)
          self.SpecificUserModalData.list = res.data.rows;
        }, err => {})
    },
    favourableEditModal_open(itemData) {
      console.log('favourableEditModal_open_itemData', itemData)
      var initData = itemData;
      var parkIdList = [];
      var inputParks = [];
      api.fetchGet('/compaign/parkList.do', {
        'compaignId': initData.id
      }).then(res => {
        console.log(res)
        if (res.status == 1) {
          var data = res.data;
          for (var i = 0; i < data.length; i++) {
            parkIdList.push(data[i].parkId);
            inputParks.push(data[i].parkName);
          }
        }
      }, err => {});
      var reliefType = function () {
        switch (initData.reliefType) {
          case "AMOUNT_DEDUCTION":
            return "1"
            break;
          case "FREE":
            return "0"
            break;
          case "AMOUNT_DISCOUNT":
            return "2"
            break;
          default:
            break;
        };
      }()
      var validTimePeriod = [new Date('1997-01-01 ' + initData.validTimePeriod.split('-')[0] + ':00'),
        new Date('1997-01-01 ' + initData.validTimePeriod.split('-')[1] + ':59'),
      ];

      var favourableModalData = {
        compaignId: initData.id,
        couponName: initData.couponName,
        applyScene: initData.applyScene.split(','),
        parkIdList: parkIdList,
        inputParks: inputParks,
        validWeekStr: initData.validWeek.split(','),
        validTime: [initData.validFrom, initData.validTo],
        applySceneType: initData.applySceneType || initData.applySceneType == 0 ? initData.applySceneType.toString() : '',
        couponType: '',
        faceValue: '',
        faceValue1: reliefType == 1 ? initData.faceValue : '',
        faceValue2: reliefType == 2 ? initData.faceValue : '',
        useRuleMin: initData.useRuleShow.split("-")[0],
        useRuleMax: initData.useRuleShow.split("-")[1].replace("元", ""),
        validTimePeriod: validTimePeriod,
        validTimePeriod1: initData.validTimePeriod.split('-')[0],
        validTimePeriod2: initData.validTimePeriod.split('-')[1],
        applyObjStr: initData.applyObj.split(','),
        maxReliefValue: initData.maxReliefValue.toString(),
        reliefType: reliefType ? reliefType.toString() : '',
        specialUserFile: '',
      };
      this.favourableModal_open(favourableModalData,'edit');
    },
    favourableModal_open(initData,type) {
      var _this = this;
      if(type == 'new'){
        _this.getParkTreeFirst()
        _this.selFileName = ''
        _this.handleStatus = 'new'
      }else if(type == 'edit'){
        _this.handleStatus = 'edit'
        _this.selFileName = ''
      }
      var today = [new Date(moment().format('YYYY-MM-DD 00:00:00')), new Date(moment().format('YYYY-MM-DD 23:59:59'))];
      _this.favourableModalData = {
        compaignId: '',
        couponName: '',
        applyScene: [],
        parkIdList: [],
        inputParks: [],
        validWeekStr: ['1','2','3','4','5','6','7'],
        validTime: _this.afterMonthArr,
        applySceneType: '',
        couponType: '',
        faceValue: '',
        faceValue1: '',
        faceValue2: '',
        useRuleMin: '',
        useRuleMax: '',
        validTimePeriod: _this.afterMonthArr,
        validTimePeriod1: '',
        validTimePeriod2: '',
        applyObjStr: [],
        maxReliefValue: '',
        reliefType: '0',
        specialUserFile: '',
      };
      console.log('initData===editdata', initData)
      if (initData) {
        _this.favourableModalData = initData;
      }
      _this.toOpenModal('favourableModal', 1);

    },
    favourableModal_save(event, formName) {
      var _this = this;
      _this.$refs[formName].validate((valid) => {
        if (valid) {
          var params = _this.favourableModalData;
          if (params.parkIdList.length < 1) {
            // icon: 0:普通提示 1：正确的提示 2： 错误提示
            // time: 不填默认1000ms
            _this.showToast("请至少选择一个停车场", 2, 2000)
            return;
          }
          if (Number(params.useRuleMax) <= Number(params.useRuleMin)) {
            // icon: 0:普通提示 1：正确的提示 2： 错误提示
            // time: 不填默认1000ms
            _this.showToast("停车费条件填写的数值有误", 2, 2000)
            return;
          }
          if(typeof(params.parkIdList)=='String'){
            let str = params.parkIdList
            let pIdArr = str.split(',')
            params.parkIdList = pIdArr
          }
          params.parkIdList = params.parkIdList.join(',');
          params.validWeekStr = params.validWeekStr.join(',');
          params.applyObjStr = params.applyObjStr.join(',');
          // params.applyScene = params.applyScene.join(',');
          params.applyScene = '';
          params.validTime = _this.formatDate(params.validTime[0]) + ' - ' + _this.formatDate(params.validTime[1]);
          if (Number(params.reliefType) == 1) {
            params.faceValue = params.faceValue1
          } else {
            params.faceValue = params.faceValue2
          }
          params.validTimePeriod1 = params.validTimePeriod[0].Format("hh:mm");
          params.validTimePeriod2 = params.validTimePeriod[1].Format("hh:mm");
          api.fetchPost('compaign/save.do', params).then(response => {
            console.log('favourableModal_save ==== response', response);
            if (response.status == 1) {
              // icon: 0:普通提示 1：正确的提示 2： 错误提示
              // time: 不填默认1000ms
              _this.showToast(response.message, 1, 2000);
              _this.resetForm('favourable_form');
              _this.closed('favourableModal');
              _this.getList();
            } else {
              _this.showToast(res.message, 2, 2000)
              return;
            }
          }, err => {
            console.log(err);
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //获取列表
    getItemList(aparams) {
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);
      // API.coupon.GetTraderListData(params)
      api.fetchGet('/compaign/list.do', params)
        .then(res => {
          console.log('getListResult', res)
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        }, err => {})
    },
    toBatchOprators(name, data) {
      switch (name) {
        case 'bt_correct':
          this.toAdjust(data);
          break;
        default:
          break;
      }
    },
    toAdjust() {},
    exportData() {
      let self = this;
      let params = {};
      params = $.extend({}, params, this.searchParams);
      this.toExport('monthTicketBill/detail/export.do', params);
    },
    downSpecialTemplate() {
      var self = this;
      window.location.href = encodeURI("/mgr/excelTemplate/compaign_coupon_special_user.csv");
    }

  },
  filters: {
    validWeek: function (value) {
      var str = value.split(",")
      var newstr = str.map(function (val) {
        switch (Number(val)) {
          case 1:
            return "星期一"
            break;
          case 2:
            return "星期二"
            break;
          case 3:
            return "星期三"
            break;
          case 4:
            return "星期四"
            break;
          case 5:
            return "星期五"
            break;
          case 6:
            return "星期六"
            break;
          case 7:
            return "星期天"
            break;

          default:
            break;

        }

      })
      return newstr.join("，");

    },
    applyObj: function (value) {
      var str = value.split(",")
      var newstr = str.map(function (val) {
        switch (Number(val)) {
          case 0:
            return "一点停手机用户"
            break;
          case 1:
            return "一点停微信用户"
            break;
          case 2:
            return "游客"
            break;
          case 3:
            return "特定用户"
            break;
          default:
            break;

        }

      })
      return newstr.join("，");

    },
    applySceneType: function (value) {
      switch (value) {
        case 0:
          return "公开"
          break;
        case 1:
          return "内部"
          break;
        default:
          break;

      }
      // }
    },
    applyScene: function (value) {
      var str = value.split(",")
      var newstr = str.map(function (val) {
        switch (Number(val)) {
          case 0:
            return "扫二维码"
            break;
          case 1:
            return "一点停微信"
            break;
          case 2:
            return "一点停APP"
            break;
          default:
            break;

        }

      })
      return newstr.join("，");

    },
    reliefType: function (value) {

      switch (value) {
        case "AMOUNT_DEDUCTION":
          return "扣减优惠"
          break;
        case "FREE":
          return "全免优惠"
          break;
        case "AMOUNT_DISCOUNT":
          return "折扣优惠"
          break;
        default:
          break;

      }
    },
    validStatus: function (value) {

      switch (value) {
        case "VALID":
          return "启用"
          break;
        case "FROZE":
          return "禁用"
          break;
        default:
          break;

      }
    }

  }

}
